package com.sunricher.telinkblemesh.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.sunricher.telinkblemesh.R;
import com.sunricher.telinkblemeshlib.MeshCommand;
import com.sunricher.telinkblemeshlib.MeshDeviceType;
import com.sunricher.telinkblemeshlib.MeshManager;
import com.sunricher.telinkblemeshlib.MeshOtaFile;
import com.sunricher.telinkblemeshlib.MeshOtaManager;
import com.sunricher.telinkblemeshlib.MqttMessage;
import com.sunricher.telinkblemeshlib.NaturalLightManager;
import com.sunricher.telinkblemeshlib.callback.DeviceEventCallback;
import com.sunricher.telinkblemeshlib.db.RoomSceneManager;
import com.sunricher.telinkblemeshlib.models.NaturalLight;
import com.sunricher.telinkblemeshlib.mqttdeviceevent.AbstractMqttDeviceEvent;
import com.sunricher.telinkblemeshlib.mqttdeviceevent.StateEvent;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

public class MainActivity extends AppCompatActivity {

    static final String LOG_TAG = "MainActivity";

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_PRIVILEGED
    };
    private static String[] PERMISSIONS_LOCATION = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_PRIVILEGED
    };

    private void checkPermissions(){
        int permission1 = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permission2 = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN);
        if (permission1 != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    1
            );
        } else if (permission2 != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_LOCATION,
                    1
            );
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermissions();

        MeshManager.getInstance().init(getApplication());

        MeshManager.getInstance().setDeviceEventCallback(new DeviceEventCallback() {
            @Override
            public void didUpdateEvent(MeshManager manager, AbstractMqttDeviceEvent event) {

                String message = MqttMessage.deviceEvent(event, "maginawin");
                Log.i(LOG_TAG, "didUpdateEvent " + message);

                switch (event.getEventType()) {

                    case state:
                        if (event.getClass() == StateEvent.class) {

                            StateEvent stateEvent = (StateEvent) event;
                            Log.i(LOG_TAG, "State event meshDevices.count " + stateEvent.getMeshDevices().size());
                        }
                        break;

                    default:
                        break;
                }

            }
        });

        Button defaultNetworkBtn = (Button) findViewById(R.id.default_network_btn);
        defaultNetworkBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, DefaultNetworkActivity.class);
                MainActivity.this.startActivity(intent);
            }
        });

        Button androidTelinkBtn = (Button) findViewById(R.id.android_telink_btn);
        androidTelinkBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, AndroidTelinkActivity.class);
                MainActivity.this.startActivity(intent);
            }
        });

        Button allDevices = (Button) findViewById(R.id.all_devices_btn);
        allDevices.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, AllDevicesActivity.class);
                MainActivity.this.startActivity(intent);
            }
        });

        Button otaBtn = findViewById(R.id.ota_btn);
        otaBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int address = 0x01;
                MeshDeviceType deviceType = new MeshDeviceType(0x01, 0x3C);
                String currentFW = "V6.B";
                MeshOtaFile otaFile = MeshOtaManager.getInstance().getLatestOtaFile(deviceType, currentFW);
                Log.i(LOG_TAG, "is need ota? " + otaFile.isNeedUpdate(currentFW));

                MeshOtaManager.getInstance().setCallback(new MeshOtaManager.Callback() {
                    @Override
                    public void didUpdateFailed(MeshOtaManager manager, MeshOtaManager.FailedReason reason) {
                        Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void didUpdateProgress(MeshOtaManager manager, int progress) {
                        Toast.makeText(MainActivity.this, "p " + progress, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void didUpdateComplete() {
                        Toast.makeText(MainActivity.this, "successful", Toast.LENGTH_SHORT).show();
                    }
                });
                // MeshOtaManager.getInstance().startOta(address, MeshNetwork.factory, otaFile, MainActivity.this);
            }
        });

        Button resetNfcBtn = findViewById(R.id.reset_nfc_device);
        resetNfcBtn.setOnClickListener(v -> {

            if (!isNfcAvailable()) {
                Toast.makeText(this, "NFC Unsupported", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!isNfcEnabled()) {
                Toast.makeText(this, "NFC Disabled", Toast.LENGTH_SHORT).show();
                return;
            }
            // Go to reset nfc activity
            Intent intent = new Intent(this, ResetNfcActivity.class);
            startActivity(intent);
        });

        NaturalLightManager.getInstance().startGetNaturalLight(0x00, NaturalLight.Mode.mode1);

//        System.out.println("onCreate start");
        RoomSceneManager.getInstance(getApplicationContext()).test();
//        System.out.println("onCreate end");
    }

    private boolean isNfcAvailable() {
        return NfcAdapter.getDefaultAdapter(this) != null;
    }

    private boolean isNfcEnabled() {
        NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
        if (adapter == null) { return false; }
        return adapter.isEnabled();
    }
}